package com.lzh.shijicloudstack.controller;

import com.lzh.shijicloudstack.common.R;
import com.lzh.shijicloudstack.common.ResultUtil;
import com.lzh.shijicloudstack.config.MinIOConfig;
import com.lzh.shijicloudstack.config.enums.request.ErrorCodeEnum;
import com.lzh.shijicloudstack.utils.MinIOUtils;
import io.minio.messages.Bucket;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Api(tags = "文件模块")
@Slf4j
@RestController
@RequestMapping(value = "/file")
public class FileController {

    @Autowired
    private MinIOConfig prop;

    @ApiOperation(value = "查看存储bucket是否存在")
    @GetMapping("/bucketExists")
    public R<Boolean> bucketExists(@RequestParam("bucketName") String bucketName) throws Exception {
        return ResultUtil.success(MinIOUtils.bucketExists(bucketName));
    }

    @ApiOperation(value = "创建存储bucket")
    @GetMapping("/makeBucket")
    public R<Boolean> makeBucket(String bucketName) {
        return ResultUtil.success(MinIOUtils.makeBucket(bucketName));
    }

    @ApiOperation(value = "删除存储bucket")
    @GetMapping("/removeBucket")
    public R<Boolean> removeBucket(String bucketName) throws Exception {
        return ResultUtil.success(MinIOUtils.removeBucket(bucketName));
    }

    @ApiOperation(value = "获取全部bucket")
    @GetMapping("/getAllBuckets")
    public R<List<Bucket>> getAllBuckets() throws Exception {
        return ResultUtil.success(MinIOUtils.getAllBuckets());
    }

    @ApiOperation(value = "文件上传返回url")
    @PostMapping("/upload")
    public R<?> upload(@RequestParam("file") MultipartFile file) {
        String objectName = MinIOUtils.upload(file);
        if (null != objectName) {
            return ResultUtil.success(prop.getEndpoint() + "/" + prop.getBucketName() + "/" + objectName);
        }
        return ResultUtil.error(ErrorCodeEnum.OPERATION_ERROR);
    }

    @ApiOperation(value = "图片/视频预览")
    @GetMapping("/preview")
    public R<String> preview(@RequestParam("fileName") String fileName) {
        return ResultUtil.success(MinIOUtils.preview(fileName));
    }

    @ApiOperation(value = "文件下载")
    @GetMapping("/download")
    public R<?> download(@RequestParam("fileName") String fileName, HttpServletResponse res) {
        MinIOUtils.download(fileName, res);
        return ResultUtil.success(null);
    }

    @ApiOperation(value = "删除文件", notes = "根据url地址删除文件")
    @PostMapping("/delete")
    public R<String> remove(String url) {
        String objName = url.substring(url.lastIndexOf(prop.getBucketName() + "/") + prop.getBucketName().length() + 1);
        MinIOUtils.remove(objName);
        return ResultUtil.success(objName);
    }

}
